<?php

namespace magein\utils;

class Result
{
    /**
     * @var int
     */
    protected int $code = 0;

    /**
     * @var string
     */
    protected string $msg = '';

    /**
     * @var mixed
     */
    protected mixed $data = null;

    /**
     * @param string|null $message
     * @param int $code
     * @param $data
     * @return Result
     */
    public static function error(string $message = null, int $code = 1, $data = null): Result
    {
        $result = new self();
        $result->code = $code;
        $result->msg = $message ?: '';
        $result->data = $data;

        return $result;
    }

    /**
     * @param null $data
     * @param string|null $message
     * @param int $code
     * @return Result
     */
    public static function success($data = null, string $message = null, int $code = 0): Result
    {
        $result = new self();
        $result->code = $code;
        $result->msg = $message ?: '';
        $result->data = $data;

        return $result;
    }

    /**
     * @param $result
     * @param string|null $message
     * @return Result
     */
    public static function auto($result, string $message = null): Result
    {
        if ($result) {
            $code = 1;
            $data = $result;
            $message = $message ?: '操作成功';
        } else {
            $code = 0;
            $data = null;
            $message = $message ?: '操作失败';
        }

        $result = new self();
        $result->code = $code;
        $result->msg = $message;
        $result->data = $data;

        return $result;
    }

    /**
     * @return mixed
     * @throws \Exception
     */
    public function response()
    {
        throw new \Exception(json_encode($this->toArray()));
    }

    /**
     * @return array
     */
    public function toArray(): array
    {
        return [
            'code' => $this->getCode(),
            'msg' => $this->getMsg(),
            'data' => $this->getData()
        ];
    }

    /**
     * @return int
     */
    public function getCode(): int
    {
        return intval($this->code);
    }

    /**
     * @return string
     */
    public function getMsg(): string
    {
        return is_string($this->msg) ? $this->msg : '';
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }
}